package com.sangananitsolution.fragments;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.PeriodFormat;
import org.joda.time.format.PeriodFormatter;

import LoadImgfromUrl.ImageLoader;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sangananitsolution.database.FavouirteItemCRUD;
import com.sangananitsolution.gogoproject.R;

public class MySearch_SearchOption_OnSubmit extends Fragment {
	int count = 0;
	ArrayList<String> dsecriptionmain;
	ArrayList<String> suburbmain;
	ArrayList<String> imagesmain;
	ArrayList<String> startdatemain;
	ArrayList<String> startimemain;
	ArrayList<String> finishtimemain;
	ArrayList<String> productIDmain;
	ArrayList<String> garageSaleTitlemain;
	ArrayList<String> oneOrTwoDaySalemain;
	ArrayList<String> unitStreeNomain;
	ArrayList<String> streeNamemain;
	ArrayList<String> citymain;
	ArrayList<String> statemain;
	ArrayList<String> postCodearraymain;
	ArrayList<String> earlyBirdMessagemain;
	ArrayList<String> badWeatherMessagemain;
	ArrayList<String> goodsTypearraymain;
	ArrayList<String> currentUsermain;
	ArrayList<String> longitudemain;
	ArrayList<String> latitudemain;

	Context contextmain;
	ListView listView;
	CustomAdapter singlayoutforrow;

	public MySearch_SearchOption_OnSubmit(Context context,
			ArrayList<String> dec, ArrayList<String> suburbmain,
			ArrayList<String> imagesurl, ArrayList<String> startdate,
			ArrayList<String> startime, ArrayList<String> finishtime,
			ArrayList<String> productID, ArrayList<String> garageSaleTitle,
			ArrayList<String> oneOrTwoDaySale, ArrayList<String> unitStreeNo,
			ArrayList<String> streeName, ArrayList<String> city,
			ArrayList<String> state, ArrayList<String> postCodearray,
			ArrayList<String> earlyBirdMessage,
			ArrayList<String> badWeatherMessage,
			ArrayList<String> goodsTypearray, ArrayList<String> currentUser,
			ArrayList<String> longitude, ArrayList<String> latitude) {

		this.contextmain = context;
		this.dsecriptionmain = dec;
		this.suburbmain = suburbmain;
		this.imagesmain = imagesurl;
		this.startdatemain = startdate;
		this.startimemain = startime;
		this.finishtimemain = finishtime;
		this.productIDmain = productID;
		this.garageSaleTitlemain = garageSaleTitle;
		this.oneOrTwoDaySalemain = oneOrTwoDaySale;
		this.unitStreeNomain = unitStreeNo;
		this.citymain = city;
		this.statemain = state;
		this.postCodearraymain = postCodearray;
		this.earlyBirdMessagemain = earlyBirdMessage;
		this.badWeatherMessagemain = badWeatherMessage;
		this.goodsTypearraymain = goodsTypearray;
		this.currentUsermain = currentUser;
		this.longitudemain = longitude;
		this.latitudemain = latitude;
		this.streeNamemain = streeName;
	}

	public MySearch_SearchOption_OnSubmit() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.mysearchproduct, container, false);
		listView = (ListView) view.findViewById(R.id.listviewmyserachProdct);
		if ((suburbmain != null) && (dsecriptionmain != null)) {
			singlayoutforrow = new CustomAdapter(getActivity(), suburbmain,
					dsecriptionmain, startdatemain, startimemain,
					finishtimemain);
		} else {

			Toast.makeText(getActivity(), "nothing to display",
					Toast.LENGTH_LONG).show();
		}

		listView.setAdapter(singlayoutforrow);

		view.findViewById(R.id.imgmygarbagecreatenew).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// to move to back page

						android.app.FragmentManager fragmentManager = getFragmentManager();
						android.app.FragmentTransaction fragmentTransaction = fragmentManager
								.beginTransaction();

						fragmentTransaction
								.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

						fragmentTransaction.addToBackStack(null);
						fragmentTransaction.replace(R.id.mainfragmentlayout,
								new Mysearch_SearchOption());
						fragmentTransaction.commit();

					}
				});
		return view;
	}

	class CustomAdapter extends ArrayAdapter<String> {
		int[] images;
		String[] text;
		Context context1;
		ArrayList<String> dsecription;
		ArrayList<String> suburb;
		ArrayList<String> statdate;
		ArrayList<String> starttime;
		ArrayList<String> finishtimemain;

		public CustomAdapter(Context context, ArrayList<String> dse,
				ArrayList<String> sub, ArrayList<String> startdate,
				ArrayList<String> startimr, ArrayList<String> finshtime) {

			super(context, R.layout.singlerowlayout, R.id.txtsuburb, dse);

			this.dsecription = dse;
			this.context1 = context;
			this.suburb = sub;
			this.statdate = startdate;
			this.starttime = startimr;
			this.finishtimemain = finshtime;
		}

		
		@SuppressLint("ViewHolder")
		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			LayoutInflater inflater = (LayoutInflater) context1
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View view = inflater.inflate(R.layout.singlerowlayout,
					parent, false);

			Button button = (Button) view.findViewById(R.id.setreaminertime);
			
			String setremain = setTime(starttime.get(position),
					statdate.get(position), finishtimemain.get(position));

			button.setText(setremain);
			view.findViewById(R.id.bttoaddfavoirte).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							// change the color of button to yellow if add to
							// favorite
							if (count == 0) {
								// add the data to db
								String longitut = null, latitute = null;
								try {
									longitut = longitudemain.get(position);
									latitute = latitudemain.get(position);
								} catch (Exception e) {
									// handle exception
									latitute = null;
									longitut = null;
								}
								FavouirteItemCRUD userInfoCRUD = new FavouirteItemCRUD(
										getActivity());
								userInfoCRUD.insertAllData(
										imagesmain.get(position),
										garageSaleTitlemain.get(position),
										startdatemain.get(position),
										oneOrTwoDaySalemain.get(position),
										startimemain.get(position),
										finishtimemain.get(position),
										unitStreeNomain.get(position),
										streeNamemain.get(position),
										suburb.get(position),
										citymain.get(position),
										statemain.get(position),
										postCodearraymain.get(position),
										dsecription.get(position),
										earlyBirdMessagemain.get(position),
										badWeatherMessagemain.get(position),
										goodsTypearraymain.get(position),
										currentUsermain.get(position),
										longitut, latitute,
										productIDmain.get(position));
								count = 1;
								view.findViewById(R.id.bttoaddfavoirte)
										.setBackgroundResource(
												R.drawable.delatefromdbbotton);
							} else {

								FavouirteItemCRUD userInfoCRUD = new FavouirteItemCRUD(
										getActivity());
								userInfoCRUD.deleteAllData(productIDmain
										.get(position));

								count = 0;
								view.findViewById(R.id.bttoaddfavoirte)
										.setBackgroundResource(
												R.drawable.starnoselected);

							}

						}
					}

			);

			String image_url;
			ImageView imageView = (ImageView) view
					.findViewById(R.id.imageproduct);

			try {
				// Image url
				image_url = "http://garagesalesagogo.com.au//"
						+ imagesmain.get(position).replace("~/", "");

			} catch (Exception e) {
				image_url = "http://garagesalesagogo.com.au//ProductImages/201522017214_986.png";

			}

			int loader = R.drawable.ic_launcher;
			ImageLoader imageLoader = new ImageLoader(getActivity());

			imageLoader.DisplayImage(image_url, loader, imageView);

			TextView textView = (TextView) view.findViewById(R.id.txtsuburb);

			TextView textView2 = (TextView) view
					.findViewById(R.id.txtdiscription);

			textView.setText(suburb.get(position));
			textView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// open the view in new page
					/*
					 * Toast.makeText(getActivity(), "hello", Toast.LENGTH_LONG)
					 * .show();
					 */
					android.app.FragmentManager fragmentManager = getFragmentManager();
					android.app.FragmentTransaction fragmentTransaction = fragmentManager
							.beginTransaction();

					fragmentTransaction
							.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

					fragmentTransaction.addToBackStack(null);

					String longitut = null, latitute = null;
					try {
						longitut = longitudemain.get(position);
						latitute = latitudemain.get(position);
					} catch (Exception e) {
						// handle exception
						latitute = null;
						longitut = null;

					}
					fragmentTransaction.replace(
							R.id.mainfragmentlayout,
							new MySearch_SearchOption_OnSubmit_ItemClick(
									getActivity(), dsecriptionmain
											.get(position), suburbmain
											.get(position), imagesmain
											.get(position), startdatemain
											.get(position), startimemain
											.get(position), finishtimemain
											.get(position), productIDmain
											.get(position), garageSaleTitlemain
											.get(position), oneOrTwoDaySalemain
											.get(position), unitStreeNomain
											.get(position), streeNamemain
											.get(position), citymain
											.get(position), statemain
											.get(position), postCodearraymain
											.get(position),
									earlyBirdMessagemain.get(position),
									badWeatherMessagemain.get(position),
									goodsTypearraymain.get(position),
									currentUsermain.get(position), longitut,
									latitute,imagesmain));
					fragmentTransaction.commit();

				}
			});
			textView2.setText(dsecription.get(position));

			textView2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// open the view in new page

					android.app.FragmentManager fragmentManager = getFragmentManager();
					android.app.FragmentTransaction fragmentTransaction = fragmentManager
							.beginTransaction();

					fragmentTransaction
							.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

					fragmentTransaction.addToBackStack(null);
					String longitut = null, latitute = null;
					try {
						longitut = longitudemain.get(position);
						latitute = latitudemain.get(position);
					} catch (Exception e) {
						// shandle exception
						latitute = null;
						longitut = null;

					}
					fragmentTransaction.replace(
							R.id.mainfragmentlayout,
							new MySearch_SearchOption_OnSubmit_ItemClick(
									getActivity(), dsecriptionmain
											.get(position), suburbmain
											.get(position), imagesmain
											.get(position), startdatemain
											.get(position), startimemain
											.get(position), finishtimemain
											.get(position), productIDmain
											.get(position), garageSaleTitlemain
											.get(position), oneOrTwoDaySalemain
											.get(position), unitStreeNomain
											.get(position), streeNamemain
											.get(position), citymain
											.get(position), statemain
											.get(position), postCodearraymain
											.get(position),
									earlyBirdMessagemain.get(position),
									badWeatherMessagemain.get(position),
									goodsTypearraymain.get(position),
									currentUsermain.get(position), longitut,
									latitute,imagesmain));
					fragmentTransaction.commit();

				}
			});

			return view;
		}
	}

	public String setTime(String startTime, String startDate,
			String finishtimemain) {

		// finding the system current time and date of system
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
		Date date = new Date();
		String currentDate = sdf.format(date).toString();

		// getting minutes and hours from server
		String str = startTime;
		int hours = 0, minutes = 0;
		DateFormat formatters = new SimpleDateFormat("h:mm a");
		Date dates;
		try {
			dates = formatters.parse(str);

			hours = dates.getHours();
			minutes = dates.getMinutes();
		} catch (ParseException e1) {

			e1.printStackTrace();
		}

		String salesStartDate = startDate + " " + hours + ":" + minutes;

		DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");

		DateTimeFormatter formatter = DateTimeFormat.forPattern(
				"MM/dd/yyyy HH:mm").withZone(timeZone);

		DateTime dateTimeStart = formatter.parseDateTime(currentDate);
		DateTime dateTimeStop = formatter.parseDateTime(salesStartDate);
		Period period = new Period(dateTimeStart, dateTimeStop);
		PeriodFormatter periodFormatter = PeriodFormat.getDefault();
		String output = periodFormatter.print(period);

		// getremainingsalestime(output,finishtimemain);

		String splitdatetime[] = output.split("and");

		for (int i = 0; i < splitdatetime.length; i++)
			splitdatetime[i] = splitdatetime[i].trim();

		String result = "", tagvalue = "";

		for (int i = 0; i < splitdatetime.length; i++) {
			String datetime = splitdatetime[i];
			String[] timePosNegativesplit = datetime.split(",");
			String timePosNegative = timePosNegativesplit[0];
			String[] diftime = timePosNegative.split(" ");
			String dtime = diftime[0];

			String setremaing;
			if (Integer.parseInt(dtime) < 0) {

				result = "Go Go";

				break;
			}

			String tag = diftime[1];
			if (tag.equals("hours")) {
				tagvalue = "h";

			} else if (tag.equals("day"))

			{

				tagvalue = "d";

			}

			else if (tag.equals("week")) {
				tagvalue = "w";

			} else {

				tagvalue = "m";
			}

			result = result + " " + dtime + tagvalue;

		}

		// setremaing=dtime+"h"+" "+dtimes+"m";

		return result;

	}

	public String getremainingsalestime(String outputs, String finishtime) {

		DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");

		DateTimeFormatter formatter = DateTimeFormat.forPattern(
				"YYYY-MM-dd HH:mm:ss").withZone(timeZone);

		DateTime dateTimeStart = formatter.parseDateTime(outputs);
		DateTime dateTimeStop = formatter.parseDateTime(finishtime);
		Period period = new Period(dateTimeStart, dateTimeStop);
		PeriodFormatter periodFormatter = PeriodFormat.getDefault();
		String output = periodFormatter.print(period);
		String splitdatetime[] = output.split("and");
		String datetime = splitdatetime[0];
		String[] timePosNegativesplit = datetime.split(",");
		String timePosNegative = timePosNegativesplit[0];
		String[] diftime = timePosNegative.split(" ");
		String dtime = diftime[0];

		return null;

	}

}
